package com.zyf.cloud.services.userservice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyf.cloud.common.exception.MyException;
import com.zyf.cloud.common.utils.MD5Utils;
import com.zyf.cloud.services.userservice.config.RedisAPI;
import com.zyf.cloud.services.userservice.entity.UserEntity;
import com.zyf.cloud.services.userservice.mapper.UserMapper;
import com.zyf.cloud.services.userservice.service.MailService;
import com.zyf.cloud.services.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    //正则表达式校验密码
    public static final String PW_PATTERN = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";

    @Autowired
    private UserMapper userMapper;

    @Resource
    private MailService mailService;

    @Resource
    private RedisAPI redisAPI;


    //判断用户是否存在
    @Override
    public boolean isUserExist(String id) {
        if (userMapper.selectById(id) == null) {
            return false;
        } else {
            return true;
        }
    }

    //根据提供的id拿密码
    @Override
    public String getPasswordByUserId(String id) {
        return userMapper.selectById(id).getPassword();
    }

    //用户注册
    @Override
    public Boolean regist2(UserEntity user) {
        if (!user.getPassword().matches(PW_PATTERN)) {
            throw new MyException("密码格式错误!");
        }
        String newPd2 = MD5Utils.MD5(user.getPassword());
        user.setPassword(newPd2);
        return userMapper.addUser2(user);
    }

//    //修改某一用户的密码
//    @Override
//    public int upUserPassword(Integer id,String password, String newpassword) {
//        UserEntity userEntity = upUserPasswordRedis(id, password, newpassword);
//        if (ObjectUtils.isEmpty(userEntity)) {
//            return 1;
//        }
//        return 0;
//    }

    @CachePut(cacheNames = "user-list", key = "#id")
// @Cacheable(cacheNames = "user-list", key = "#id")
    @Override
    public UserEntity upUserPasswordRedis(Integer id, String password, String newpassword) {
        UserEntity user = userMapper.selectById(id);
        if (ObjectUtils.isEmpty(user)) {
            return user;
        }
        if (!MD5Utils.MD5(password).equals(user.getPassword())) {
            throw new MyException("旧密码错误!");
        }
        if (!newpassword.matches(PW_PATTERN)) {
            throw new MyException("密码格式错误!");
        }
        user.setPassword(MD5Utils.MD5(newpassword));
        user.updateById();
        return user;
    }

    //查询用户存不存在
    @Override
    public int findUserByLgName(String name) {
        // todo
        return userMapper.findUserByLgName(name);
    }

    /**
     * 将结果缓存，当参数相同时，不会执行方法，从缓存中取
     */
    @Cacheable(cacheNames = "user-list", key = "#id")
    @Override
    public UserEntity findUserById(Integer id) {
        System.out.println("===> findUserById(id), id = " + id);
        return this.userMapper.selectById(id);
    }

    @Override
    public UserEntity findByToken(String token) {
        return null;
    }

    //用户登入
    @Override
    // @Cacheable(cacheNames = "user-list", key = "#id")
    public UserEntity login(String name, String password) {
        String md5Password = MD5Utils.MD5(password);
        return userMapper.findUserByNameAndPwdv1(name, md5Password);
    }

    //根据id修改
    @Override
    public int update(UserEntity user) {
        int userEntity = userMapper.updateById(user);
        if (ObjectUtils.isEmpty(userEntity)) {
            return 1;
        }
        return 0;
    }

    //根据id物理删除
    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    /**
     * 移除缓存，根据指定key
     *
     * @param user
     */
    @CacheEvict(cacheNames = "user-list", key = "#user.id")
    public Boolean deleteById(UserEntity userEntity) {
        System.out.println("===> deleteById(), user = " + userEntity);
        //this.userMapper.deleteById(userEntity.getId());
        return true;
    }

    //通过id查询数据
    @Override
    public UserEntity selectById(Integer id) {
        return this.userMapper.selectById(id);

    }

    /**
     * 移除当前 cacheName下所有缓存
     */
    @Override
    @CacheEvict(cacheNames = "user-list", allEntries = true)
    public Boolean deleteAll() {
        System.out.println("===> deleteAll()");
        return true;
    }

    @Autowired
    private BatchInsertTest batchTest;

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void testTrans() {
        for (int i = 100; i < 110; i++) {
            try {
                batchTest.testInsert(i);
//                testInsert(i);
            } catch (Exception e) {
                e.printStackTrace();
            }
//          /  batchTest.testInsert(i);
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void testInsert(int i) {
        System.out.println("插入" + i);
        UserEntity entity = new UserEntity();
        entity.setId(i);
        entity.setName("zyf" + i);
        entity.setPhoneNumber("1111111111" + i);
        entity.setStatus(1);
        entity.setCreateTime(new Date());
        entity.setLastLoginTime(new Date());
        entity.setLastUpdateTime(new Date());
        this.save(entity);
        if (i == 106) {
            throw new MyException("测试");
        }
    }
        /**
         * 邮箱注册
         */
        @Override
        public void insertUser (UserEntity user) throws Exception {
            //1、添加用户
            //userMapper.insertItripUser(user);
            userMapper.insert(user);
            //2、生成激活码， new Date().toLocaleString()生成日期和时间，
            //格式如：2019-1-25 22:56:32，然后进行32位的MD5加密
            String activationCode = MD5Utils.getMd5(new Date().toLocaleString(), 32);
            //3、发送邮件
            mailService.sendActivationMail(user.getEmail(), activationCode);
            //4、激活码存入Redis中
            redisAPI.set("activation:" + user.getEmail(), 30 * 60, activationCode);
    }

    /**
     * 根据用户名查找用户
     * @param username
     */
    @Override
    public UserEntity findByUsername(String username){
        Map<String, Object> param=new HashMap();
        param.put("name", username);
        List<UserEntity> list= userMapper.getItripUserListByMap(param);
        if(list.size()>0) {
            return list.get(0);
        } else {
            return null;
        }
    }
    /**
     * 邮箱激活
     * @param mail 邮箱地址
     * @param code 激活码(使用MD5进行32位的加密)
     * @return true/false，true表示验证成功
     */
    @Override
    public boolean activate(String mail, String code) throws Exception {
        //1、验证激活码
        String value = redisAPI.get("activation:" + mail);
        if (value.equals(code)) {
            UserEntity user =findByUsername(mail);
            //2、更新用户
            user.setStatus(1);  //激活账户
            //user.setUserType(0); //自注册用户
            user.setId(user.getId());
            userMapper.updateItripUser(user);
            return true;
        } else {
            return false;
        }
    }
}


